package com.zhx.experiment.controller;

import com.sun.org.apache.xpath.internal.operations.Mod;
import com.zhx.experiment.entity.Blog;
import com.zhx.experiment.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.LinkedList;
import java.util.List;

@Controller
public class BlogController {
    @Autowired
    BlogService blogService;

    @RequestMapping(value = "toBg_mg")
    public String toBg_mg(ModelMap model,String username){
        model.addAttribute("username",username);

        List<Blog> blogs = blogService.findAllBlog();
        model.addAttribute("blogs",blogs);
        return "article_management";
    }

    @RequestMapping(value = "createBlog")
    public String create(Model model,String username,Blog blog){
        model.addAttribute("username",username);
        blogService.addBlog(blog);

        List<Blog> blogs = blogService.findAllBlog();
        model.addAttribute("blogs",blogs);
        return "article_management";
    }

    @RequestMapping(value = "searchBlog")
    public String search(Model model, String username,String sc_title){
        if("".equals(sc_title)){
            List<Blog> blogs=blogService.findAllBlog();
            model.addAttribute("username",username);
            model.addAttribute("blogs",blogs);
            return "article_management";
        }

        Blog blog=blogService.queryBlogByName(sc_title);
        List<Blog> blogs=new LinkedList<>();
        if(blog!=null)
            blogs.add(blog);
        model.addAttribute("username",username);
        model.addAttribute("blogs",blogs);
        return "article_management";
    }

    @RequestMapping(value = "updateBlog")
    public String update(Model model,String username,Blog blog,String old_title){
        model.addAttribute("username",username);

        Blog newBlog=blogService.queryBlogByName(old_title);
        newBlog.setTitle(blog.getTitle());
        newBlog.setContent(blog.getContent());
        blogService.updateBlog(newBlog);

        List<Blog> blogs = blogService.findAllBlog();
        model.addAttribute("blogs",blogs);
        return "article_management";
    }

    @RequestMapping(value = "deleteBlog")
    public String delete(Model model,String username,String dl_title){
        model.addAttribute("username",username);

        System.out.println(username);
        System.out.println(dl_title);
        blogService.deleteBlogByName(dl_title);

        List<Blog> blogs = blogService.findAllBlog();
        model.addAttribute("blogs",blogs);
        return "article_management";
    }
}
